<?php
namespace Shop\Controller;
use Think\Controller;

class IndexController extends Controller {
	protected function _initialize() {
		//===系统信息======
		$system = D('System')->find(1);
		$this->assign('system', $system);
	}
	public function index() {
		if (IS_POST) {
			//验证码
			// $verify = new \Think\Verify();
			// if (!$verify->check(I('post.passcode'))) {
			//     $this->error('验证码错误!');
			//     return false;
			// }
			//登录
			$userModel = D('User');
			if (!($userModel->create($_POST, 4) && $userModel->login('商家'))) {
				$this->error($userModel->getError());
			}
			$this->redirect('Notice/list');
			return true;
		}
		if (session('商家')) {
			$this->redirect('Notice/list');
		} else {
			//登录页面
			$this->display('login');
		}
	}

	// public function passcode() {
	//     $verify = new \Think\Verify(['length'=>4, 'useNoise'=>false, 'useCurve'=>false,]);
	//     echo $verify->entry();
	// }

	public function register() {
		if (IS_POST) {
			if ($_POST['verify-code'] != session('verifyCode')) {
				$this->error('验证码有误,请重新填写!');
			}
	        if (D('User')->where(['username'=>$_POST['username'], 'type'=>$_POST['type']])->find()) {
	            $this->error('您已经注册过，请勿重复注册!');
	        }
			$upload = new \Think\Upload(); // 实例化上传类
			$upload->maxSize = 99999999; // 设置附件上传大小
			$upload->rootPath = './Public/file/'; // 设置附件上传根目录
			$upload->savePath = ''; // 设置附件上传（子）目录
			$upload->autoSub = false;
			$info = $upload->upload();
			if ($info) {
				$_POST['photo'] = $info['photo']['savename'];
				$_POST['justification'] = $info['justification']['savename'];
			}
			//增加用户
			$model = D('User');
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$userId = $model->add();

			//增加商家
			$_POST['principal_id'] = $userId;
			$model = D('UserShop');
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->add();
			$this->success('申请成功,审核通过后即可登录商家后台,建议使用电脑登录www..116lyw.com/Shop!', U('Index/index'));
		}
		$this->display();
	}

	public function logout() {
		session('商家', null);
		$this->success('注销成功!', U('Index/index'));
	}

}
